package com.atguigu.yygh.common.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * @author 孔德成
 * @slogan 致敬大师，致敬未来的你
 * @date 2021/9/8 8:46 上午
 * @desc
 */
public class JwtHelper {
    private static long tokenExpiration = 24 * 60 * 60 * 1000;
    private static String tokenSignKey = "123456";

    /**
     * JWT 生成
     *
     * @param userId   用户 id
     * @param userName 用户名
     */
    public static String createToken(Long userId, String userName) {
        HashMap<String, Object> payload = MapUtil.newHashMap(2);
        payload.put("userId", userId);
        payload.put("userName", userName);
        return JWTUtil.createToken(payload, tokenSignKey.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * JWT 解析
     */
    public static Long getUserId(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        return Convert.toLong(jwt.getPayload("userId"));
    }

    public static String getUserName(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        return Convert.toStr(jwt.getPayload("userName"));

    }

    /**
     * JWT 验证
     */
    public static boolean verify(String token) {
        return JWTUtil.verify(token, tokenSignKey.getBytes(StandardCharsets.UTF_8));
    }

}
